package com.douyin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.douyin.dto.PageActionsDTO;
import com.douyin.dto.Result;
import com.douyin.entity.Follows;
import com.douyin.mapper.FollowsMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.douyin.service.IFollowService;
import com.douyin.utils.BaseContext;
import com.douyin.vo.FollowUserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户关注关系表 服务实现类
 * </p>
 *
 * @author k
 * @since 2025-07-27
 */
@Service
public class FollowsServiceImpl extends ServiceImpl<FollowsMapper, Follows> implements IFollowService {

    @Autowired
    FollowsMapper followsMapper;
    @Override
    public Result userFollow(Long followUserId) {
        //检查followUser是否为空
        if (followUserId == null) {
            return Result.fail("followUserId不能为空");
        }
        //检查followUser是否存在
        Follows follow = followsMapper.selectById(followUserId);
        if (follow == null) {
            return Result.fail("followUser不存在");
        }
        //检查是否已经关注
        LambdaQueryWrapper<Follows > queryWrapper = new LambdaQueryWrapper<>();
        Long currentId = BaseContext.getCurrentId();
        queryWrapper.eq(Follows::getUserId, currentId).eq(Follows::getFollowUserId, followUserId);
        Follows follows = followsMapper.selectOne(queryWrapper);
        if (follows ==null){
            Follows follow1 = new Follows();
            follow1.setUserId(currentId);
            follow1.setFollowUserId(followUserId);
            follow1.setStatus(1);
            followsMapper.insert(follow1);
            return Result.ok(follow1);
        }
        if (follows.getStatus()==0) {
            //关注
            follows.setStatus(1);
            followsMapper.updateById(follows);
            return Result.ok("关注成功");
        }
        if (follows.getStatus()==1) {
            //取消关注
            follows.setStatus(0);
            followsMapper.updateById(follows);
            return Result.ok(follows);
        }
        return Result.fail("关注状态异常");
    }

    @Override
    public IPage<FollowUserVO> getFollowingList(IPage<FollowUserVO> page, Long targetUserId) {
        // 1. 调用 Mapper 进行分页查询，获取基础的用户信息列表
        IPage<FollowUserVO> userPage = followsMapper.selectFollowingPage(page, targetUserId);

        // 2. 补充 isFollowed 状态
        fillIsFollowedStatus(userPage.getRecords());

        return userPage;
    }

    @Override
    public IPage<FollowUserVO> getFollowersList(IPage<FollowUserVO> page, Long targetUserId) {
        // 1. 调用 Mapper 进行分页查询，获取基础的用户信息列表
        IPage<FollowUserVO> userPage = followsMapper.selectFollowersPage(page, targetUserId);

        // 2. 补充 isFollowed 状态
        fillIsFollowedStatus(userPage.getRecords());

        return userPage;
    }

    @Override
    public Result getFollowings(PageActionsDTO pageActionsDTO) {
        PageActionsDTO pageActionsDTO1 = checkFollowsDTO(pageActionsDTO);
        if (pageActionsDTO1 == null) {
            return Result.fail("参数错误");
        }
        Page<FollowUserVO> pageInfo = new Page<>(pageActionsDTO.getPageCount(), pageActionsDTO.getPageSize());
        IPage<FollowUserVO> followingList = getFollowingList(pageInfo, pageActionsDTO.getId());
        return Result.ok(followingList);
    }

    @Override
    public Result getFollowers(PageActionsDTO pageActionsDTO) {
        PageActionsDTO pageActionsDTO1 = checkFollowsDTO(pageActionsDTO);
        if (pageActionsDTO1 == null) {
            return Result.fail("参数错误");
        }
        Page<FollowUserVO> pageInfo = new Page<>(pageActionsDTO.getPageCount(), pageActionsDTO.getPageSize());
        IPage<FollowUserVO> followersList = getFollowersList(pageInfo, pageActionsDTO.getId());
        return Result.ok(followersList);
    }
    private PageActionsDTO checkFollowsDTO(PageActionsDTO pageActionsDTO) {
        if (pageActionsDTO == null) {
            return null;
        }
        if (pageActionsDTO.getId() == null&&BaseContext.getCurrentId() == null) {
            return null;
        }
        if (BaseContext.getCurrentId() == null) {
            return null;
        }
        if (pageActionsDTO.getId() == null) {
            pageActionsDTO.setId(BaseContext.getCurrentId());
        }
        if (pageActionsDTO.getPageCount() == null) {
            pageActionsDTO.setPageCount(1);
        }
        if (pageActionsDTO.getPageSize() == null) {
            pageActionsDTO.setPageSize(10);
        }
        return pageActionsDTO;
    }

    /**
     * 填充用户列表的 "isFollowed" 状态 (核心逻辑)
     * @param userList 用户列表
     */
    private void fillIsFollowedStatus(List<FollowUserVO> userList) {
        // 如果列表为空，或者用户未登录，则无需处理
        if (CollectionUtils.isEmpty(userList)) {
            return;
        }
        Long currentUserId = BaseContext.getCurrentId();
        if (currentUserId == null) {
            // 用户未登录，所有人的 isFollowed 都为 false
            userList.forEach(user -> user.setFollowed(false));
            return;
        }

        // 1. 提取列表中所有用户的ID
        List<Long> userIdList = userList.stream().map(FollowUserVO::getId).collect(Collectors.toList());

        // 2. 一次性查询出当前登录用户在这些用户中关注了哪些人
        LambdaQueryWrapper<Follows> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Follows::getUserId, currentUserId)
                .in(Follows::getFollowUserId, userIdList);

        List<Follows> followedRelations = this.list(queryWrapper);

        // 3. 将已关注的用户ID放入一个Set中，便于快速查找
        Set<Long> followedUserIdSet = followedRelations.stream()
                .map(Follows::getFollowUserId)
                .collect(Collectors.toSet());

        // 4. 遍历用户列表，设置 isFollowed 状态
        userList.forEach(user -> {
            // 如果用户的ID在已关注的Set中，则设置为true，否则为false
            user.setFollowed(followedUserIdSet.contains(user.getId()));
        });
    }
}
